import { plainToClass } from "class-transformer";
import { validate } from "class-validator";

export declare type ClassConstructor<T> = {
    new(...args: unknown[]): T;
};


export abstract class BaseEntity {
    /**
     * 验证当前电影对象
     */
    public async validateThis(skipMissing = false): Promise<string[]> {
        const error = await validate(this, {
            skipMissingProperties: skipMissing,
        })
        const temp = error.map(e => {
            return e.constraints ? Object.values(e.constraints) : [];
        })
        const result = temp.reduce((pre, cur) => {
            return pre.concat(cur)
        }, [])
        return result;
    }

    /**
    * # 将一个平面对象转换为一个实体类对象
    * @param plainObject  
    * @returns 
    */
    protected static baseTransform<T>(cls: ClassConstructor<T>, plainObject: object): T {
        if (plainObject instanceof cls) {
            return plainObject;
        }

        return plainToClass(cls, plainObject)
    }
}
